"""A collection of ORM sqlalchemy models for Myapp"""

# Import the datetime class from the datetime module to handle timestamps.
from datetime import datetime

# Import the base Model class from Flask-AppBuilder, which this model will inherit from.
from flask_appbuilder import Model
# Import various column types and the Column class from SQLAlchemy to define the database schema.
from sqlalchemy import (
    Column,
    DateTime,
    ForeignKey,
    Integer,
    String,
    Text,
)
# Import the relationship function from SQLAlchemy's ORM to define relationships between models.
from sqlalchemy.orm import relationship

# Import the Flask application instance to access its configuration.
from myapp.app import app
# Import a custom base model that may contain shared logic or properties.
from myapp.models.base import MyappModelBase
# Import the custom user model to create a foreign key relationship.
from myapp.models.model_user import MyUser

# Retrieve the application's configuration object.
config = app.config
# Get a specific configuration value for a custom password store, if it exists.
custom_password_store = config.get('SQLALCHEMY_CUSTOM_PASSWORD_STORE')
# Get a specific configuration value for a stats logger, if it exists.
stats_logger = config.get('STATS_LOGGER')

# Define a constant string to mask passwords in logs.
PASSWORD_MASK = 'X' * 10


# Define the Log class, which maps to the 'logs' table in the database.
# It inherits from Flask-AppBuilder's Model and a custom MyappModelBase.
class Log(Model, MyappModelBase):
    """ORM object used to log Myapp actions to the database"""

    # Specifies the name of the database table for this model.
    __tablename__ = 'logs'

    # Defines the primary key column for the table, an auto-incrementing integer.
    id = Column(Integer, primary_key=True)

    # Defines a foreign key column that links to the 'id' in the 'ab_user' table.
    user_id = Column(Integer, ForeignKey('ab_user.id'))
    # Defines a many-to-one relationship to the MyUser model.
    # This allows easy access to the user object associated with a log entry (e.g., log.user).
    user = relationship(MyUser, foreign_keys=[user_id])
    # Defines a column to store the name or description of the action being logged.
    action = Column(String(512))
    # Defines a column to store the HTTP method of the request (e.g., GET, POST).
    method = Column(String(50))
    # Defines a column to store the path of the request URL.
    path = Column(String(200))
    # Defines a column to store the HTTP status code of the response.
    status = Column(Integer)
    # Defines a column to store a JSON string, likely for request/response payloads or other metadata.
    json = Column(Text)
    # Defines a column to store the timestamp of when the log entry was created.
    dttm = Column(
        DateTime, default=datetime.now
    )  # 不要使用datetime.now()不然是程序启动的固定时间了
       # English translation of the comment above:
       # Do not use datetime.now() otherwise it will be a fixed time when the application starts.
       # Using `datetime.now` as a callable ensures it's executed at the time of insertion.
    
    # Defines a column to store the duration of the request in milliseconds.
    duration_ms = Column(Integer)
    # Defines a column to store the HTTP referrer of the request.
    referrer = Column(String(1024))

    # This dictionary maps internal column names (keys) to their display names in Chinese (values).
    # It is used for providing user-friendly labels in the user interface, likely overriding the base class definition.
    label_columns = {
        'user': '用户',
        'action': '函数',
        'method': '方法',
        'path': '网址',
        'status': '状态',
        'dttm': '时间',
        'duration_ms': '响应延迟',
        'referrer': '相关人',
    }
